/*
Filename: UCMgrRegist.java
Precondition: manager enter a invalid administrator name and password
Post-condition: manager registers in the system
Main success Scenario:
1. Manager selects to register
2. Manager enters name and password
3. Manager clicks ‘register’ button
4. System checks manager name and password are valid
5. System checks with database that manager is unique.
6. System registers manager and password with database
7. System registers the manager information.
8. System displays message “Registration Successful
9. System updates the main UI.
2a. Extensions: System detects invalid register:
 System display “invalid manager register “message'.
 */

package ucm;

/**
 *
 * @author Mark
 */
import model.UsersModel;
import model.DatabaseModel;
import view.marRegister;

import javax.swing.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;

public class UCMgrRegist implements UCController {

    private UsersModel user;

    public UCMgrRegist() {
        user = new UsersModel("", "", "", "", "");
    }

    public UCMgrRegist(UsersModel user) {
        // System retrieves username and password
        this.user = user;
    }

    public UCMgrRegist(marRegister marRegister) {
        // System retrieves username and password
        this.user = marRegister.getUserModel();
    }

    // STEP 1 - User Selects Register
    public boolean run() {
        boolean registeredSuccessful = false;
        // STEP 2 - System retrieves username and password
        // This step is integrated into the constructor or
        // may be specified by using run(UserModel)
        // STEP 3 - System checks username and password are valid (greater than 4 characters)
        if (validDetails()) {
            //Step 4 - System checks with database that username is unique
            if (uniqueUser()){
                //Step 5 - System registers username and password with database
                if (registerUser()) {
                    // STEP 6 - System displays 'Registered Successfully' message
                    JOptionPane.showMessageDialog(new JFrame(),
                            "Registered Successfully!",
                            "Success",
                            JOptionPane.INFORMATION_MESSAGE);
                      new ucm.UCDispalyMgrLogin();
                    registeredSuccessful = true;
                } else {
                    JOptionPane.showMessageDialog(new JFrame(),
                            "Registration failed for unknown reason",
                            "Error Message",
                            JOptionPane.ERROR_MESSAGE);
                }
            } else {
                //Step 4a - System displays 'username not unique' message
                JOptionPane.showMessageDialog(new JFrame(),
                        "Username already exists, please choose another",
                        "Error Message",
                        JOptionPane.ERROR_MESSAGE);
            }
        } else {
            //Step 3a - System displays 'invalid user details' message
            JOptionPane.showMessageDialog(new JFrame(),
                    "Username or password invalid (must be between 5 and 10 characters)",
                    "Error Message",
                    JOptionPane.ERROR_MESSAGE);
        }
        return registeredSuccessful;
    }

    // STEP 1 - User Selects Register
    public void run(UsersModel user) {
        // STEP 2 - System retrieves username and password
        this.user = user;
        // STEP 3 onwards
        run();
    }

    private boolean validDetails() {
        // Check the length of the username and password
        return (user.getUsername().length() >= 4) &&
                (user.getUsername().length() <= 16) &&
                (user.getPassword().length() >= 4) &&
                (user.getPassword().length() <= 16);
    }

    private boolean uniqueUser() {
        boolean unique = false;
        String username = user.getUsername();

        Connection con = DatabaseModel.getInstance().getConnection();

        try {
            Statement stmt = con.createStatement(ResultSet.CONCUR_UPDATABLE,
                    ResultSet.CONCUR_UPDATABLE);

            ResultSet res = stmt.executeQuery("SELECT * FROM managers WHERE " +
                    "mname = '" + username + "'");

            unique = !(res.first() && username.equals(res.getString("mname")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unique;

    }

    private boolean registerUser(){
        boolean register = false;
        String username = user.getUsername();
        String password = user.getPassword();
        String phone = user.getPhone();
        String email = user.getemail();
        String purview = user.getpurview();
          if(purview.equals("mgr")){
        DatabaseModel dbModel = DatabaseModel.getInstance();

        Connection con = dbModel.getConnection();
        try {
            Statement stmt = con.createStatement(ResultSet.CONCUR_UPDATABLE,
                    ResultSet.CONCUR_UPDATABLE);

            stmt.executeUpdate("INSERT INTO managers (`MNAME`, `MPASSWORD`, `MPHONE`, `MEMAIL`) values('" + username + "', '" + password + "', " + phone +", '" + email +"')");
            //database problems.
            register = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
          }
        return register;
    }
}
